<script setup>
import { ref, computed, onMounted } from 'vue'
import { showToast } from 'vant'

// 蓝信平台相关
const isLanxinPlatform = computed(() => {
  // 检查是否在蓝信环境中
  return typeof window !== 'undefined' && window.lanxin
})

// 蓝信鉴权状态
const lanxinAuthStatus = ref('pending') // pending, success, failed

// 选择的图片列表
const selectedImages = ref([])
const maxImages = 5

// 页面信息
const pageUrl = ref('')
const userAgent = ref('')

// 蓝信对象检查
const lanxinExists = ref(false)
const lanxinConfigExists = ref(false)
const lanxinChooseImageExists = ref(false)

// 蓝信JSAPI鉴权
async function lanxinAuth() {
  if (!isLanxinPlatform.value) {
    console.log('非蓝信环境，跳过鉴权')
    return false
  }
  
  try {
    console.log('开始蓝信JSAPI鉴权...')
    
    // 检查蓝信对象是否完全加载
    if (!window.lanxin || !window.lanxin.config) {
      console.log('蓝信对象未完全加载，等待...')
      await new Promise(resolve => setTimeout(resolve, 500))
      
      if (!window.lanxin || !window.lanxin.config) {
        throw new Error('蓝信对象加载超时')
      }
    }
    
    // 调用蓝信鉴权接口
    const result = await window.lanxin.config({
      // 这里需要你的应用配置信息
      // 具体参数需要根据你的蓝信应用配置来填写
      // 通常包括 appId, timestamp, nonceStr, signature 等
      appId: '13960192-14303232', // 替换为你的蓝信应用ID
      timestamp: Date.now(),
      nonceStr: Math.random().toString(36).substr(2, 15),
      signature: 'your_signature', // 这个需要后端生成
      jsApiList: ['chooseImage'] // 需要使用的接口列表
    })
    
    console.log('蓝信鉴权成功:', result)
    lanxinAuthStatus.value = 'success'
    return true
    
  } catch (error) {
    console.error('蓝信鉴权失败:', error)
    lanxinAuthStatus.value = 'failed'
    showToast('蓝信鉴权失败，将使用原生文件选择')
    return false
  }
}

// 重试蓝信鉴权
async function retryLanxinAuth() {
  console.log('重试蓝信鉴权...')
  lanxinAuthStatus.value = 'pending'
  return await lanxinAuth()
}

// 蓝信选择图片（需要先鉴权）
async function lanxinChooseImage(options = {}) {
  if (!isLanxinPlatform.value) {
    showToast('当前环境不支持蓝信接口')
    return null
  }
  
  // 检查鉴权状态
  if (lanxinAuthStatus.value !== 'success') {
    console.log('蓝信未鉴权，尝试重新鉴权...')
    const authSuccess = await lanxinAuth()
    if (!authSuccess) {
      showToast('蓝信鉴权失败，无法使用图片选择功能')
      return null
    }
  }
  
  try {
    const result = await window.lanxin.chooseImage({
      count: options.count || 1, // 最多可以选择的图片张数
      sizeType: options.sizeType || ['original', 'compressed'], // 所选的图片的尺寸
      sourceType: options.sourceType || ['album', 'camera'], // 选择图片的来源
      ...options
    })
    
    console.log('蓝信选择图片成功:', result)
    return result
  } catch (error) {
    console.error('蓝信选择图片失败:', error)
    showToast('选择图片失败')
    return null
  }
}

// 处理蓝信选择的图片
async function handleLanxinImages(tempFilePaths) {
  try {
    for (const tempFilePath of tempFilePaths) {
      // 检查是否超过最大数量
      if (selectedImages.value.length >= maxImages) {
        showToast(`最多只能选择${maxImages}张图片`)
        break
      }
      
      // 将蓝信的临时文件路径转换为File对象
      const file = await convertLanxinTempFileToFile(tempFilePath)
      if (file) {
        // 创建预览URL
        const reader = new FileReader()
        reader.onload = (e) => {
          const newImage = {
            url: e.target.result,
            file: { uid: Date.now() + Math.random() },
            fileName: file.name,
            originalFile: file // 保存原始文件对象
          }
          selectedImages.value.push(newImage)
          showToast(`图片 ${file.name} 选择成功`)
        }
        reader.readAsDataURL(file)
      }
    }
  } catch (error) {
    console.error('处理蓝信图片失败:', error)
    showToast('处理图片失败')
  }
}

// 将蓝信临时文件转换为File对象
async function convertLanxinTempFileToFile(tempFilePath) {
  try {
    // 蓝信返回的是临时文件路径，需要转换为File对象
    // 这里使用fetch获取文件内容
    const response = await fetch(tempFilePath)
    const blob = await response.blob()
    
    // 生成文件名
    const fileName = `lanxin_image_${Date.now()}.jpg`
    
    // 创建File对象
    const file = new File([blob], fileName, { type: blob.type })
    
    return file
  } catch (error) {
    console.error('转换蓝信文件失败:', error)
    showToast('文件转换失败')
    return null
  }
}

// 选择图片
async function chooseImage() {
  if (selectedImages.value.length >= maxImages) {
    showToast(`最多只能选择${maxImages}张图片`)
    return
  }
  
  // 优先使用蓝信接口
  if (isLanxinPlatform.value) {
    const remainingCount = maxImages - selectedImages.value.length
    const result = await lanxinChooseImage({
      count: remainingCount,
      sizeType: ['compressed'], // 使用压缩图片，减少文件大小
      sourceType: ['album', 'camera']
    })
    
    if (result && result.tempFilePaths) {
      // 处理蓝信返回的图片
      await handleLanxinImages(result.tempFilePaths)
    }
  } else {
    // 降级到原生文件选择
    const fileInput = document.createElement('input')
    fileInput.type = 'file'
    fileInput.accept = 'image/*'
    fileInput.multiple = true
    
    fileInput.onchange = (event) => {
      const files = event.target.files
      if (files && files.length > 0) {
        Array.from(files).forEach(file => {
          if (selectedImages.value.length < maxImages) {
            const reader = new FileReader()
            reader.onload = (e) => {
              const newImage = {
                url: e.target.result,
                file: { uid: Date.now() + Math.random() },
                fileName: file.name,
                originalFile: file
              }
              selectedImages.value.push(newImage)
              showToast(`图片 ${file.name} 选择成功`)
            }
            reader.readAsDataURL(file)
          }
        })
      }
    }
    
    fileInput.click()
  }
}

// 删除图片
function deleteImage(index) {
  selectedImages.value.splice(index, 1)
  showToast('图片删除成功')
}

// 清空所有图片
function clearAllImages() {
  selectedImages.value = []
  showToast('已清空所有图片')
}

// 页面初始化
onMounted(() => {
  console.log('=== 蓝信图片选择测试页面 ===')
  
  // 安全地获取页面信息
  if (typeof window !== 'undefined') {
    pageUrl.value = window.location.href
    userAgent.value = navigator.userAgent
    console.log('页面URL:', pageUrl.value)
    console.log('User Agent:', userAgent.value)
    
    // 检查蓝信对象
    lanxinExists.value = typeof window.lanxin !== 'undefined'
    lanxinConfigExists.value = !!(window.lanxin && window.lanxin.config)
    lanxinChooseImageExists.value = !!(window.lanxin && window.lanxin.chooseImage)
  }
  
  // 检查蓝信环境并进行鉴权
  if (isLanxinPlatform.value) {
    console.log('✅ 检测到蓝信环境，开始鉴权...')
    // 自动进行蓝信鉴权
    setTimeout(async () => {
      await lanxinAuth()
    }, 1000) // 延迟1秒执行，确保蓝信JS完全加载
  } else {
    console.log('⚠️ 未检测到蓝信环境，将使用原生文件选择')
  }
})
</script>

<template>
  <div class="test-page">
    <div class="header">
      <h1>蓝信图片选择测试</h1>
      <p class="subtitle">测试蓝信平台的图片选择功能</p>
    </div>

    <!-- 环境信息 -->
    <div class="info-section">
      <div class="info-item">
        <span class="label">蓝信环境:</span>
        <span class="value" :class="{ 'success': isLanxinPlatform, 'warning': !isLanxinPlatform }">
          {{ isLanxinPlatform ? '✅ 是' : '⚠️ 否' }}
        </span>
      </div>
      <div class="info-item">
        <span class="label">鉴权状态:</span>
        <span class="value" :class="{
          'success': lanxinAuthStatus === 'success',
          'warning': lanxinAuthStatus === 'pending',
          'error': lanxinAuthStatus === 'failed'
        }">
          {{ 
            lanxinAuthStatus === 'success' ? '✅ 成功' : 
            lanxinAuthStatus === 'pending' ? '⏳ 进行中' : 
            '❌ 失败' 
          }}
        </span>
      </div>
      <div class="info-item">
        <span class="label">已选图片:</span>
        <span class="value">{{ selectedImages.length }}/{{ maxImages }}</span>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <van-button 
        type="primary" 
        size="large" 
        round 
        @click="chooseImage"
        :disabled="selectedImages.length >= maxImages"
        class="choose-btn"
      >
        {{ selectedImages.length >= maxImages ? '已达到最大数量' : '选择图片' }}
      </van-button>
      
      <van-button 
        v-if="lanxinAuthStatus === 'failed' && isLanxinPlatform"
        type="warning" 
        size="large" 
        round 
        @click="retryLanxinAuth"
        class="retry-btn"
      >
        重试蓝信鉴权
      </van-button>
      
      <van-button 
        v-if="selectedImages.length > 0"
        type="danger" 
        size="large" 
        round 
        @click="clearAllImages"
        class="clear-btn"
      >
        清空所有图片
      </van-button>
    </div>

    <!-- 图片预览区域 -->
    <div class="images-section">
      <h3>已选择的图片</h3>
      
      <div v-if="selectedImages.length === 0" class="no-images">
        <van-icon name="photo-o" size="48" />
        <p>还没有选择图片</p>
        <p class="tip">点击上方按钮选择图片</p>
      </div>
      
      <div v-else class="images-grid">
        <div 
          v-for="(image, index) in selectedImages" 
          :key="image.file.uid"
          class="image-item"
        >
          <img :src="image.url" :alt="image.fileName" class="preview-image" />
          <div class="image-info">
            <div class="file-name">{{ image.fileName }}</div>
            <div class="file-size">{{ (image.originalFile.size / 1024).toFixed(1) }}KB</div>
          </div>
          <div class="delete-btn" @click="deleteImage(index)">
            <van-icon name="cross" />
          </div>
        </div>
      </div>
    </div>

    <!-- 调试信息 -->
    <div class="debug-section">
      <h3>调试信息</h3>
      <div class="debug-content">
        <div class="debug-item">
          <span class="debug-label">页面URL:</span>
          <span class="debug-value">{{ pageUrl }}</span>
        </div>
        <div class="debug-item">
          <span class="debug-label">User Agent:</span>
          <span class="debug-value">{{ userAgent }}</span>
        </div>
        <div class="debug-item">
          <span class="debug-label">蓝信对象:</span>
          <span class="debug-value">{{ lanxinExists ? '存在' : '不存在' }}</span>
        </div>
        <div class="debug-item">
          <span class="debug-label">蓝信config方法:</span>
          <span class="debug-value">{{ lanxinConfigExists ? '存在' : '不存在' }}</span>
        </div>
        <div class="debug-item">
          <span class="debug-label">蓝信chooseImage方法:</span>
          <span class="debug-value">{{ lanxinChooseImageExists ? '存在' : '不存在' }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.test-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  color: white;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 700;
}

.subtitle {
  margin: 0;
  opacity: 0.8;
  font-size: 16px;
}

.info-section {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  backdrop-filter: blur(10px);
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.info-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.label {
  font-weight: 600;
  opacity: 0.9;
}

.value {
  font-weight: 700;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
}

.value.success {
  background: rgba(76, 175, 80, 0.3);
  color: #4caf50;
}

.value.warning {
  background: rgba(255, 152, 0, 0.3);
  color: #ff9800;
}

.value.error {
  background: rgba(244, 67, 54, 0.3);
  color: #f44336;
}

.action-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 30px;
}

.choose-btn {
  background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
  border: none;
  height: 50px;
  font-size: 18px;
  font-weight: 600;
}

.retry-btn {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
  border: none;
  height: 50px;
  font-size: 18px;
  font-weight: 600;
}

.clear-btn {
  background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
  border: none;
  height: 50px;
  font-size: 18px;
  font-weight: 600;
}

.images-section {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  backdrop-filter: blur(10px);
}

.images-section h3 {
  margin: 0 0 20px 0;
  text-align: center;
  font-size: 20px;
}

.no-images {
  text-align: center;
  padding: 40px 20px;
  opacity: 0.7;
}

.no-images .van-icon {
  margin-bottom: 16px;
  opacity: 0.5;
}

.no-images p {
  margin: 8px 0;
}

.tip {
  font-size: 14px;
  opacity: 0.6;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 16px;
}

.image-item {
  position: relative;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.2);
}

.preview-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.image-info {
  padding: 12px;
}

.file-name {
  font-size: 12px;
  font-weight: 600;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: 11px;
  opacity: 0.7;
}

.delete-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: rgba(244, 67, 54, 0.9);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  backdrop-filter: blur(10px);
}

.debug-section {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.debug-section h3 {
  margin: 0 0 16px 0;
  text-align: center;
  font-size: 18px;
  opacity: 0.9;
}

.debug-content {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.debug-item {
  margin-bottom: 8px;
  padding: 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.debug-label {
  color: #ffd54f;
  margin-right: 8px;
  font-weight: 600;
}

.debug-value {
  color: #81c784;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .test-page {
    padding: 16px;
  }
  
  .header h1 {
    font-size: 24px;
  }
  
  .images-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 12px;
  }
  
  .preview-image {
    height: 100px;
  }
}
</style>

<route lang="json5">
{
  name: 'Test',
  meta: {
    title: '蓝信图片选择测试'
  }
}
</route> 